<script>
import axios from "../../axios/axiosHelper";
import { Plus, Search, Edit, Delete } from '@element-plus/icons-vue';

export default {
  name: "Press",
  components: {
    Plus,
    Search,
    Edit,
    Delete
  },
  data() {
    return {
      tableData: [],
      total: 0,
      currentPage: 1,
      pageSize: 10,
      loading: false,
      searchForm: {
        field: '',
        code: ''
      },
      dialogVisible: false,
      dialogTitle: '',
      form: {
        id: '',
        name: '',
        number: '',
        address: '',
        cellphone: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入出版社名称', trigger: 'blur' },
          { min: 2, max: 50, message: '出版社名称长度应在2-50个字符之间', trigger: 'blur' }
        ],
        number: [
          { required: true, message: '请输入出版社编号', trigger: 'blur' },
          { min: 2, max: 20, message: '出版社编号长度应在2-20个字符之间', trigger: 'blur' }
        ],
        address: [
          { required: true, message: '请输入地址', trigger: 'blur' },
          { min: 5, max: 100, message: '地址长度应在5-100个字符之间', trigger: 'blur' }
        ],
        cellphone: [
          { required: true, message: '请输入电话', trigger: 'blur' }
        ]
      }
    };
  },
  created() {
    this.fetchData();
  },
  methods: {
    // 获取出版社数据
    fetchData() {
      this.loading = true;
      const params = {
        offset: (this.currentPage - 1) * this.pageSize,
        limit: this.pageSize
      };
      
      // 添加搜索条件
      if (this.searchForm.code) {
        params.code = this.searchForm.code;
      }
      
      axios.get('/press/list', { params }).then(response => {
        // 将后端返回的整数转换为字符串，方便在表单中显示
        this.tableData = response.data.rows.map(item => ({
          ...item,
          name: item.name.toString(),
          number: item.number.toString(),
          address: item.address.toString(),
          cellphone: item.cellphone.toString()
        }));
        this.total = response.data.total;
        this.loading = false;
      }).catch(error => {
        console.error('获取出版社数据失败:', error);
        this.$message.error('获取出版社数据失败');
        this.loading = false;
      });
    },
    // 处理页码变化
    handleCurrentChange(val) {
      this.currentPage = val;
      this.fetchData();
    },
    // 处理每页显示数量变化
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
      this.fetchData();
    },
    // 打开添加对话框
    handleAdd() {
      this.dialogTitle = '添加出版社';
      this.form = {
        id: '',
        name: '',
        number: '',
        address: '',
        cellphone: ''
      };
      this.dialogVisible = true;
    },
    // 编辑出版社
    handleEdit(index, row) {
      this.dialogTitle = '编辑出版社';
      this.form = JSON.parse(JSON.stringify(row));
      this.dialogVisible = true;
    },
    // 提交表单
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.loading = true;
          // 使用表单数据，不需要类型转换
          const formData = {
            ...this.form
          };
          
          if (this.form.id) {
            // 更新
            axios.put('/press/update', formData).then(response => {
              this.$message.success('更新成功');
              this.dialogVisible = false;
              this.fetchData();
              this.loading = false;
            }).catch(error => {
              console.error('更新出版社失败:', error);
              this.$message.error('更新出版社失败');
              this.loading = false;
            });
          } else {
            // 添加
            axios.post('/press/add', formData).then(response => {
              this.$message.success('添加成功');
              this.dialogVisible = false;
              this.fetchData();
              this.loading = false;
            }).catch(error => {
              console.error('添加出版社失败:', error);
              this.$message.error('添加出版社失败');
              this.loading = false;
            });
          }
        } else {
          return false;
        }
      });
    },
    // 删除出版社
    handleDelete(index, row) {
      this.$confirm('确认删除该出版社?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true;
        axios.delete(`/press/delete/${row.id}`).then(response => {
          this.$message.success('删除成功');
          this.fetchData();
          this.loading = false;
        }).catch(error => {
          console.error('删除出版社失败:', error);
          this.$message.error('删除出版社失败');
          this.loading = false;
        });
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    }
  }
}
</script>

<template>
  <div class="press-container">
    <!-- 标题栏 -->
    <div class="header">
      <div class="title-section">
        <h2 class="page-title">出版社管理</h2>
        <el-button type="primary" size="small" @click="handleAdd">
          <el-icon><Plus /></el-icon>添加出版社
        </el-button>
      </div>
      <div class="search">
        <el-input v-model="searchForm.code" placeholder="请输入关键词搜索..." clearable size="small" style="width: 250px;">
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <el-button type="primary" size="small" @click="fetchData">搜索</el-button>
      </div>
    </div>

    <!-- 表格 -->
    <div class="table-container">
      <el-table 
        :data="tableData" 
        border 
        style="width: 100%" 
        v-loading="loading"
        element-loading-text="加载中..."
        :header-cell-style="{backgroundColor: '#f5f7fa', color: '#606266'}"
        highlight-current-row
        stripe
      >
        <el-table-column type="index" width="50" align="center" label="序号"></el-table-column>
        <el-table-column prop="id" label="出版社ID" width="100" align="center"></el-table-column>
        <el-table-column prop="name" label="出版社名称" width="180" align="center"></el-table-column>
        <el-table-column prop="number" label="出版社编号" width="120" align="center"></el-table-column>
        <el-table-column prop="address" label="地址" min-width="200" align="center"></el-table-column>
        <el-table-column prop="cellphone" label="电话" width="150" align="center"></el-table-column>
        <el-table-column label="操作" width="180" align="center">
          <template #default="scope">
            <div class="operation-buttons">
              <el-tooltip content="编辑" placement="top" :hide-after="1500">
                <el-button 
                  size="small" 
                  type="primary" 
                  circle
                  @click="handleEdit(scope.$index, scope.row)"
                >
                  <el-icon><Edit /></el-icon>
                </el-button>
              </el-tooltip>
              <el-tooltip content="删除" placement="top" :hide-after="1500">
                <el-button 
                  size="small" 
                  type="danger" 
                  circle
                  @click="handleDelete(scope.$index, scope.row)"
                >
                  <el-icon><Delete /></el-icon>
                </el-button>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        background
        class="custom-pagination">
      </el-pagination>
    </div>

    <!-- 添加/编辑对话框 -->
    <el-dialog 
      :title="dialogTitle" 
      v-model="dialogVisible" 
      width="550px" 
      :close-on-click-modal="false"
      destroy-on-close
      center
      class="custom-dialog"
    >
      <div class="dialog-content">
        <el-form 
          :model="form" 
          :rules="rules" 
          ref="form" 
          label-width="120px"
          class="press-form"
          status-icon
        >
          <el-form-item label="出版社名称" prop="name">
            <el-input 
              v-model="form.name"
              placeholder="请输入出版社名称"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="出版社编号" prop="number">
            <el-input 
              v-model="form.number"
              placeholder="请输入出版社编号"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="地址" prop="address">
            <el-input 
              v-model="form.address"
              placeholder="请输入地址"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="电话" prop="cellphone">
            <el-input 
              v-model="form.cellphone"
              placeholder="请输入电话"
              clearable
            ></el-input>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false" plain>取 消</el-button>
          <el-button type="primary" @click="submitForm" :loading="loading">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.press-container {
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  height: 100%;
  width: 100%;
  box-sizing: border-box;
  overflow: auto;
}

.header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
}

.title-section {
  display: flex;
  align-items: center;
  gap: 15px;
}

.page-title {
  margin: 0;
  font-size: 20px;
  color: #303133;
  font-weight: 600;
  position: relative;
  padding-left: 12px;
}

.page-title::before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 4px;
  height: 18px;
  background-color: #409EFF;
  border-radius: 2px;
}

.search {
  display: flex;
  gap: 10px;
  align-items: center;
}

.table-container {
  background-color: #fff;
  border-radius: 6px;
  padding: 10px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
  margin-bottom: 20px;
}

.operation-buttons {
  display: flex;
  justify-content: center;
  gap: 10px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  padding-top: 15px;
  border-top: 1px solid #ebeef5;
}

.custom-pagination {
  margin-right: 10px;
}

.el-table {
  margin: 0;
  border-radius: 6px;
  overflow: hidden;
}

.el-table :deep(th) {
  background-color: #f5f7fa !important;
  color: #606266;
  font-weight: bold;
  text-align: center;
}

.el-table :deep(td) {
  text-align: center;
}

.el-button--primary {
  background-color: #409EFF;
}

.el-button--success {
  background-color: #67C23A;
}

.el-button--danger {
  background-color: #F56C6C;
}

.custom-dialog :deep(.el-dialog__header) {
  padding: 10px;
  margin: 0;
  border-bottom: 1px solid #ebeef5;
  background-color: #f5f7fa;
}

.custom-dialog :deep(.el-dialog__title) {
  font-weight: 600;
  color: #303133;
  font-size: 18px;
}

.custom-dialog :deep(.el-dialog__body) {
  padding: 20px 10px;
}

.custom-dialog :deep(.el-dialog__footer) {
  padding: 10px;
  border-top: 1px solid #ebeef5;
  background-color: #f5f7fa;
}

.dialog-content {
  max-height: 60vh;
  overflow-y: auto;
}

.press-form {
  width: 100%;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.el-form-item {
  margin-bottom: 22px;
}

.el-input {
  width: 100%;
}

/* 添加一些动画效果 */
.el-table :deep(tr) {
  transition: background-color 0.3s;
}

.el-table :deep(tr:hover) {
  background-color: #f0f9eb;
}

.el-button {
  transition: all 0.3s;
}

.el-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 响应式调整 */
@media screen and (max-width: 768px) {
  .header {
    flex-direction: column;
    gap: 15px;
  }
  
  .search {
    width: 100%;
  }
  
  .search .el-input {
    flex: 1;
  }
}
</style>